#include "Renderer.h"
#include <GL/glfw.h>
#include "Window.h"
#include "TextureLoading.h"

using namespace std;
using namespace cmn;
using namespace drawing;

namespace core {

	Store<std::string, const Texture*> Renderer::m_textureStore( LoadPng );

	Store<std::string, const Texture*> Renderer::GetTextureStore() {
		return m_textureStore;
	}

	void Renderer::DrawTexture( const Texture* texture, const Transform& transform, float width, float height ) {
		Vec3 center( transform.Vec.X, transform.Vec.Y, 0.0f );
		DrawTexture( texture, center, transform.Rot, width, height );
	}

	void Renderer::DrawTexture( const Texture* texture, const Vec3& center, float width, float height ) {
		DrawTexture( texture, center, 0.0f, width, height );
	}

	void Renderer::DrawTexture( const Texture* texture, const Vec3& center, float angle, float width, float height ) {
		glPushMatrix();

		glTranslatef( center.X, center.Y, 0.0f );
		glRotatef( ToDegrees( -angle ), 0.0f, 0.0f, 1.0f );

		float right = -width / 2;
		float left = width / 2;
		float top = height / 2;
		float bottom = -height / 2;


		glEnable( GL_ALPHA_TEST );
		glEnable( GL_BLEND );	 // Turn Blending On
		glDisable( GL_DEPTH_TEST ); // Turn Depth Testing Off
		glEnable( GL_TEXTURE_2D );

		glColor4f( 1.0f, 1.0f, 1.0f, 1.0f );

		glBindTexture( GL_TEXTURE_2D, texture->GetGlId() );
		glBegin( GL_QUADS );
		glTexCoord2f( 0.0f, 0.0f );
		glVertex3f( left, bottom,  0.1f );
		glTexCoord2f( 1.0f, 0.0f );
		glVertex3f( right, bottom,  0.1f );
		glTexCoord2f( 1.0f, 1.0f );
		glVertex3f( right,  top,  0.1f );
		glTexCoord2f( 0.0f, 1.0f );
		glVertex3f( left,  top,  0.1f );
		glEnd();
		glBindTexture( GL_TEXTURE_2D, 0 );

		glPopMatrix();

		glDisable( GL_TEXTURE_2D );
		glEnable( GL_DEPTH_TEST );
		glDisable( GL_BLEND );
		glDisable( GL_ALPHA_TEST );
	}
}
